# 使用Python 3.11官方镜像作为基础镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV DISPLAY=:99
ENV DEBIAN_FRONTEND=noninteractive

# 安装系统依赖和Chrome
RUN apt-get update && apt-get install -y \
    # 基础工具
    wget \
    curl \
    gnupg2 \
    software-properties-common \
    apt-transport-https \
    ca-certificates \
    # Chrome依赖
    fonts-liberation \
    libasound2 \
    libatk-bridge2.0-0 \
    libatk1.0-0 \
    libatspi2.0-0 \
    libcups2 \
    libdbus-1-3 \
    libdrm2 \
    libgtk-3-0 \
    libnspr4 \
    libnss3 \
    libxcomposite1 \
    libxdamage1 \
    libxfixes3 \
    libxkbcommon0 \
    libxrandr2 \
    xdg-utils \
    # 虚拟显示
    xvfb \
    # 字体支持
    fonts-wqy-zenhei \
    fonts-wqy-microhei \
    ttf-wqy-zenhei \
    ttf-wqy-microhei \
    && rm -rf /var/lib/apt/lists/*

# 添加Google Chrome仓库并安装Chrome
RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
    && apt-get update \
    && apt-get install -y google-chrome-stable \
    && rm -rf /var/lib/apt/lists/*

# 复制requirements文件并安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

# 创建必要的目录
RUN mkdir -p /app/browser_data \
    && mkdir -p /app/uploads \
    && mkdir -p /app/logs \
    && mkdir -p /app/static/uploads

# 设置权限
RUN chmod +x /app/run.py

# 创建启动脚本
RUN echo '#!/bin/bash\n\
# 启动虚拟显示服务器\n\
Xvfb :99 -screen 0 1920x1080x24 &\n\
\n\
# 等待Xvfb启动\n\
sleep 2\n\
\n\
# 启动应用\n\
python run.py\n\
' > /app/start.sh && chmod +x /app/start.sh

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:8000/ || exit 1

# 启动命令
CMD ["/app/start.sh"]
